package sw.EngAdroid;

import java.util.ArrayList;
import java.util.List;

import netcode.client.Client;
import netcode.helper.ClientMessageListener;
import netcode.helper.NetcodeHelper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class NetPlay extends Activity implements ClientMessageListener {

	private boolean serverLobbyInfoReceived;
	private boolean gameLobbyInfoReceived;
	private boolean questionReceived;
	private boolean bettingOddsReceived;
	private boolean roundResultsReceived;
	private boolean endOfGameReceived;
	private Game game;
	private Client client;
	private String gameName;
	private String[] topics;
	private boolean small;
	private TextView currentName;
	private TextView questionText;
	private TextView question;
	private EditText answerText;
	private Button submit;
	private String playerName;
	private EditText[] chipsArray;
	private TextView[] guessViewArray;
	private TextView[] ratioViewArray;
	private Button bet0;
	private Player player;
	private int numplayers;
	private TextView player2View;
	private TextView player3View;
	private TextView player4View;
	private TextView player5View;
	private TextView player6View;
	private Button ready;
	private TextView hostView;
	private Button leave;
	private ArrayList<Player> players;
	private ArrayList<String> playerNames;
	private int gameID;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		if (dm.widthPixels < 1000)
			small = true;

		Intent intent = getIntent();
		Bundle info = intent.getExtras();
		gameName = info.getString("gameName");
		topics = info.getStringArray("topics");
		game = new Game();
		playerName = info.getString("playerName");
		System.out.println("Still " + playerName);
		gameID = info.getInt("gameID");

		try {
			client = new Client(NetcodeHelper.SERVER_ADDRESS,
					NetcodeHelper.SERVER_PORT, playerName, game);
			client.setListener(this);
			client.start();
			client.sendConnectionRequest();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (info.getBoolean("isHost")) {
			createGame();
		} else {
			joinGame();
		}
	}

	// Method for starting a new game
	private void createGame() {
		client.sendCreateGameRequest(gameName, 7, topics);
		if (small)
			setContentView(R.layout.lobby_host_screen6_small);
		else
			setContentView(R.layout.lobby_host_screen6);

		// show the lobby screen
		Button start = (Button) findViewById(R.id.startButton);
		final TextView[] playersView = new TextView[6];
		playersView[0] = (TextView) findViewById(R.id.hostName);
		playersView[1] = (TextView) findViewById(R.id.player2);
		playersView[2] = (TextView) findViewById(R.id.player3);
		playersView[3] = (TextView) findViewById(R.id.player4);
		playersView[4] = (TextView) findViewById(R.id.player5);
		playersView[5] = (TextView) findViewById(R.id.player6);
		Button refresh = (Button) findViewById(R.id.refreshButton2);
		Button leave = (Button) findViewById(R.id.button1);

		// Code for start button
		start.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (game.getGameID() != 0 && game.getPlayers().size() >= 3) {

					if (small) {
						setContentView(R.layout.question_screen2);
					} else
						setContentView(R.layout.question_screen);

					do {
						client.sendStartGameRequest(game.getGameID());
						sleepyTime();
					} while (!questionReceived);
					questionReceived = false;
					question();
				}
			}
		});

		// code for refresh button
		refresh.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				ArrayList<Player> players = game.getPlayers();
				// run though the player views and set their names
				for (int i = 0; i < players.size(); i++) {
					playersView[i].setText(players.get(i).getPlayer_name());
				}
			}
		});

		// code for quit button
		leave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				client.sendLeaveGameRequest(game.getGameID());
				finish();
			}
		});

	}

	private void joinGame() {
		game.setGameID(gameID);
		System.out.println(game.getGameID());
		gameLobbyInfoReceived = false;
		do {
			client.sendJoinGameRequest(gameID);
			sleepyTime();
		} while (!gameLobbyInfoReceived);
		

		if (small)
			setContentView(R.layout.lobby_guest_screen6_small);
		else
			setContentView(R.layout.lobby_guest_screen6);

		leave = (Button) findViewById(R.id.button4);
		hostView = (TextView) findViewById(R.id.hostname);
		player2View = (TextView) findViewById(R.id.player2);
		player3View = (TextView) findViewById(R.id.player3);
		player4View = (TextView) findViewById(R.id.player4);
		player5View = (TextView) findViewById(R.id.player5);
		player6View = (TextView) findViewById(R.id.player6);
		ready = (Button) findViewById(R.id.ready);

		players = game.getPlayers();
		playerNames = new ArrayList<String>();

		player5View.setText("None               ");
		player5View.setText("None               ");
		player4View.setText("None               ");
		player3View.setText("None               ");
		player2View.setText("None               ");

		for (int i = 0; i < players.size(); i++) {
			playerNames.add(players.get(i).getPlayer_name());
			if (players.get(i).getPlayer_name().equals(playerName)) {
				player = players.get(i);
			}
		}

		ready.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				do {
					players = game.getPlayers();
					playerNames = new ArrayList<String>();

					player5View.setText("None               ");
					player5View.setText("None               ");
					player4View.setText("None               ");
					player3View.setText("None               ");
					player2View.setText("None               ");

					for (int i = 0; i < players.size(); i++) {
						playerNames.add(players.get(i).getPlayer_name());
						if (players.get(i).getPlayer_name().equals(playerName)) {
							player = players.get(i);
						}
					}
					sleepyTime();
				} while (!questionReceived);
				questionReceived = false;
				question();
			}
		});

		leave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				client.sendLeaveGameRequest(game.getGameID());
				finish();
			}
		});

	}

	// question screen state
	private void question() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		if (dm.widthPixels < 1000) {
			setContentView(R.layout.question_screen2);
		} else
			setContentView(R.layout.question_screen);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);

		currentName = (TextView) findViewById(R.id.playerName);
		questionText = (TextView) findViewById(R.id.questionText);
		answerText = (EditText) findViewById(R.id.answerTextBox);
		submit = (Button) findViewById(R.id.submitAnswerButton);

		Question question = game.getQuestion();
		currentName.setText(playerName);
		questionText.setText(question.getText());
		submit.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				int numGuess = Integer
						.parseInt(answerText.getText().toString());
				bettingOddsReceived = false;
				client.sendAnswer(game.getGameID(), numGuess);
				do {
					sleepyTime();
				} while (!bettingOddsReceived);
				bet();
			}
		});

	}

	private void bet() {


		numplayers = game.getPlayers().size();
		
		switch (numplayers) {
		case 6:
			if (small)
				setContentView(R.layout.playerboard6small);
			else
				setContentView(R.layout.playerboard6);
		case 5:
			if (small)
				setContentView(R.layout.playerboard5small);
			else
				setContentView(R.layout.playerboard5);
		case 4:
			if (small)
				setContentView(R.layout.playerboard4small);
			else
				setContentView(R.layout.playerboard4);
		default:
			if (small)
				setContentView(R.layout.playerboard3small);
			else
				setContentView(R.layout.playerboard3);
		}
		
		guessViewArray = new TextView[numplayers];
		ratioViewArray = new TextView[numplayers];
		chipsArray = new EditText[numplayers];

		bet0 = (Button) findViewById(R.id.confirm01);

		// set up view elements
		switch (numplayers) {
		case 6:
			guessViewArray[5] = (TextView) findViewById(R.id.guess06);
			ratioViewArray[5] = (TextView) findViewById(R.id.ratio06);
			chipsArray[5] = (EditText) findViewById(R.id.chips06);
		case 5:
			guessViewArray[4] = (TextView) findViewById(R.id.guess05);
			ratioViewArray[4] = (TextView) findViewById(R.id.ratio05);
			chipsArray[4] = (EditText) findViewById(R.id.chips05);
		case 4:
			guessViewArray[3] = (TextView) findViewById(R.id.guess04);
			ratioViewArray[3] = (TextView) findViewById(R.id.ratio04);
			chipsArray[3] = (EditText) findViewById(R.id.chips04);

		default:
			guessViewArray[2] = (TextView) findViewById(R.id.guess03);
			ratioViewArray[2] = (TextView) findViewById(R.id.ratio03);
			chipsArray[2] = (EditText) findViewById(R.id.chips03);
			guessViewArray[1] = (TextView) findViewById(R.id.guess02);
			ratioViewArray[1] = (TextView) findViewById(R.id.ratio02);
			chipsArray[1] = (EditText) findViewById(R.id.chips02);
			guessViewArray[0] = (TextView) findViewById(R.id.guess01);
			ratioViewArray[0] = (TextView) findViewById(R.id.ratio01);
			chipsArray[0] = (EditText) findViewById(R.id.chips01);
			break;
		}

		ArrayList<Player> players = game.getPlayers();
		ArrayList<String> playerNames = new ArrayList<String>();
		for (int i = 0; i < players.size(); i++) {
			playerNames.add(players.get(i).getPlayer_name());
			if (players.get(i).getPlayer_name().equals(playerName)) {
				player = players.get(i);
			}
		}

		// Set up all the screen elements

		question = (TextView) findViewById(R.id.questionTextView1);
		TextView playerNameBet = (TextView) findViewById(R.id.gameNameView);
		playerNameBet.setText("Player name: " + playerName);

		List<Guess> guesses = game.getGuesses();
		System.out.println(numplayers);
		System.out.println(guesses.size());
		System.out.println(guessViewArray.length);
		System.out.println(ratioViewArray.length);
		for (int i = 0; i < guesses.size(); i++) {
			guessViewArray[i].setText("Guess: " + guesses.get(i).getGuess());
			ratioViewArray[i].setText("Ratio: " + guesses.get(i).getOdds());
		}

		bet0.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				List<Guess> guesses = game.getGuesses();
				int numplayers = game.getPlayers().size();
				int permChips = player.getPermanent_chips();
				int gameChips = player.getGame_chips();

				ArrayList<Bet> bets = new ArrayList<Bet>();

				int permChipsBet = 0;
				int gameChipsBet = 0;

				for (int j = 0; j < guesses.size(); j++) {
					String playerbet = chipsArray[j].getText().toString();

					if (!(playerbet.equals(""))) {
						int chipsBet = Integer.parseInt(playerbet);

						if (permChips > 0 && permChips < chipsBet) {
							permChipsBet = permChips;
							chipsBet -= permChips;
							permChips = 0;

						} else if (permChips > 0 && permChips > chipsBet) {
							permChipsBet = chipsBet;
							permChips -= chipsBet;
						}
						if (gameChips > 0 && gameChips < chipsBet) {
							gameChipsBet = gameChips;
							chipsBet -= gameChips;
							gameChips = 0;
						} else if (gameChips > 0 && gameChips > chipsBet) {
							gameChipsBet = chipsBet;
							gameChips -= chipsBet;
						}
						bets.add(new Bet(playerName, j, permChipsBet,
								gameChipsBet));
					}
				}

				client.sendSubmitBets(bets, game.getGameID());
				do {
					sleepyTime();
				} while (!roundResultsReceived);
				roundResultsReceived = false;

				results();

			}
		});

	}

	private void results() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		if (dm.widthPixels < 1000)
			setContentView(R.layout.winnings6small);
		else
			setContentView(R.layout.winnings6);

		TextView[] playerChips = new TextView[numplayers];
		switch (numplayers) {
		case 6:
			playerChips[5] = (TextView) findViewById(R.id.player5);
		case 5:
			playerChips[4] = (TextView) findViewById(R.id.player4);
		case 4:
			playerChips[3] = (TextView) findViewById(R.id.player3);
		default:
			playerChips[2] = (TextView) findViewById(R.id.player2);
			playerChips[1] = (TextView) findViewById(R.id.player1);
			playerChips[0] = (TextView) findViewById(R.id.player0);
		}
		playerChips[0] = (TextView) findViewById(R.id.player0);
		// p1chips = (TextView) findViewById(R.id.player1);
		// p2chips = (TextView) findViewById(R.id.player2);
		// p3chips = (TextView) findViewById(R.id.player3);
		// p4chips = (TextView) findViewById(R.id.player4);
		// p5chips = (TextView) findViewById(R.id.player5);
		TextView correctGuess = (TextView) findViewById(R.id.correctGuess);
		correctGuess.setText("Correct answer: "
				+ game.getQuestion().getAnswer());
		for (int i = 0; i < playerChips.length; i++) {
			playerChips[i].setText(game.getPlayers().get(i).getPlayer_name()
					+ "'s chips: " + game.getPlayers().get(i).getChips());
		}
		// p0chips.setText(game.getPlayers().get(0).getPlayer_name()
		// + "'s chips: " + game.getPlayers().get(0).getChips());
		// p1chips.setText(game.getPlayers().get(1).getPlayer_name()
		// + "'s chips: " + game.getPlayers().get(1).getChips());
		// p2chips.setText(game.getPlayers().get(2).getPlayer_name()
		// + "'s chips: " + game.getPlayers().get(2).getChips());
		// p3chips.setText(game.getPlayers().get(3).getPlayer_name()
		// + "'s chips: " + game.getPlayers().get(3).getChips());
		// p4chips.setText(game.getPlayers().get(4).getPlayer_name()
		// + "'s chips: " + game.getPlayers().get(4).getChips());
		// p5chips.setText(game.getPlayers().get(5).getPlayer_name()
		// + "'s chips: " + game.getPlayers().get(5).getChips());
		Button nextRound = (Button) findViewById(R.id.again);
		Button endGame = (Button) findViewById(R.id.endGame);
		nextRound.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				do {
					sleepyTime();
				} while (!questionReceived && !endOfGameReceived);
				if (endOfGameReceived) {
					client.sendLeaveGameRequest(game.getGameID());
					client.sendDisconnect();
					finish();
				} else {
					questionReceived = false;
					question();
				}
			}
		});

		endGame.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				client.sendLeaveGameRequest(game.getGameID());
				client.sendDisconnect();
				finish();
			}
		});

	}

	// Listener for server messages
	public void onMessageReceived(byte packetCode) {
		System.out.println("onMessageReceived() entered with code: "
				+ packetCode);
		switch (packetCode) {
		case NetcodeHelper.SERVER_LOBBY_INFO_RESPONSE:
			serverLobbyInfoReceived = true;
			break;
		case NetcodeHelper.GAME_LOBBY_INFO:
			gameLobbyInfoReceived = true;
			break;
		case NetcodeHelper.QUESTION:
			questionReceived = true;
			break;
		case NetcodeHelper.BETTING_ODDS:
			bettingOddsReceived = true;
			break;
		case NetcodeHelper.ROUND_RESULTS:
			roundResultsReceived = true;
			break;
		case NetcodeHelper.GAME_RESULTS:
			endOfGameReceived = true;
			break;
		}

	}

	public void sleepyTime() {
		try {
			Thread.sleep(NetcodeHelper.MILLISECONDS_BETWEEN_SENDING_MESSAGE);
		} catch (Exception e) {
			System.err.println(e);
		}
	}
}
